﻿# -*- coding: utf-8 -*-
import datetime
from decimal import Decimal

from openerp import models, fields, api, _
from openerp.exceptions import Warning

class bc_gathermaster(models.Model):
    _name = 'bc.gathermaster'

    name = fields.Char()
    bussines_id = fields.Many2one('bc.bussines')
    company_id = fields.Many2one('res.company', default=lambda self: self.env.user.company_id)
    dttrans = fields.Datetime(default=datetime.datetime.utcnow())
    state = fields.Selection([('draft', u'草稿'), ('audit', u'审核'), ('close', u'关闭')])
    decmoney = fields.Float()
    decbalance = fields.Float(compute='_compute_decbalance')
    remark = fields.Text()
    audit_uid = fields.Many2one('res.users')
    audit_date = fields.Datetime()
    gather_detail_ids = fields.One2many('bc.gather.detail', 'gathermaster_id')

    @api.one
    @api.constrains('decmoney', 'gather_detail_ids')
    def _check_decmoney(self):
        decmoeny = 0
        for obj in self.gather_detail_ids:
            decmoeny += obj.hxdecmoney
        if Decimal(str(self.decmoney)) <> Decimal(str(decmoeny)):
            raise ValueError(_("money not right"))

    @api.one
    @api.depends('decbalance')
    def _compute_decbalance(self):
        self.decbalance = self.get_decbalance()
        
    # 僅能刪除草稿狀態的資料
    @api.multi
    def unlink(self):
       if self.state not in ('draft') :
          raise Warning(_('state {0} can not be delete'.format(self.state)))
       return super(bc_gathermaster,self).unlink()        

    @api.model
    def create(self, vals):
        vals['name'] = self.env['ir.sequence'].get('bc.gathermaster')
        vals['state'] = 'draft'
        return super(bc_gathermaster, self).create(vals)

    # 审核
    @api.model
    def btn_audit(self):
        self.write({'state': 'audit', 'audit_uid': self.env.user.id, 'audit_date': datetime.datetime.utcnow()})
        return True

    # 反审核
    @api.model
    def btn_unaudit(self):
        self.write({'state': 'draft', 'audit_uid': False, 'audit_date': False})
        return True

    def get_decbalance(self):
        """
        用户剩余的钱 = 用户所有交的钱 - 用户所有核销的金额
        :return:
        """
        obj_payment = self.env['bc.payment']
        obj_gather_detail = self.env['bc.gather.detail']

        dec_total = obj_payment.get_bussines_total_Moeny(self.bussines_id.id)
        dec_hxtotal = obj_gather_detail.get_bussines_hx_moeny(self.bussines_id.id)
        return dec_total - dec_hxtotal

    # 更改商家
    @api.model
    @api.onchange('bussines_id')
    def _onchange_bussines(self):
        if self.bussines_id.id:
            self.decbalance = self.get_decbalance()
            obj_planbill_detail = self.env['bc.planbill.detail']
            objs = obj_planbill_detail.get_bussines_list(self.bussines_id.id)

            res = []
            for obj in objs:
                if obj.sparemoney != 0 :
                    res.append(((0, False, {'planbill_detail_id': obj.id, 'sparemoney': obj.sparemoney})))

            if not res:
                self.gather_detail_ids = False
            else:
                self.gather_detail_ids = res

    # 更改付款金额
    @api.model
    @api.onchange('bussines_id', 'decmoney')
    def _onchange_decmoney(self):
        if self.decmoney:
            decmoney = self.decmoney
            for obj in self.gather_detail_ids:
                if abs(obj.sparemoney) < abs(decmoney):
                    obj.hxdecmoney = obj.sparemoney
                    decmoney -= obj.sparemoney
                elif decmoney == 0:
                    obj.hxdecmoney = 0
                else:
                    obj.hxdecmoney = decmoney
                    decmoney = 0
